//
//  WriteStatusViewController.m
//  friendCyc
//
//  Created by roiland on 13-3-28.
//  Copyright (c) 2013年 sun. All rights reserved.
//

#import "WriteStatusViewController.h"
#import "SZTextView.h"
#import "FTWButton.h"
#import "EGOPhotoGlobal.h"
#import "MyPhotoSource.h"
#import "MyPhoto.h"
#import "FirendCircleDataSource.h"
#import "FirCirVoiceTipsView.h"
#import "recordManager.h"
#import "SpeexCodec.h"
#import "FaceBoard.h"
#import "sendFirCirNewNews.h"

#import <AVFoundation/AVFoundation.h>

#import "imageTransfrom.h"
#import "taskDataSource.h"

@interface WriteStatusViewController ()
{
    UIBarButtonItem         *voiceButton;
    UIBarButtonItem         *photoButton;
    UIBarButtonItem         *faceButton;
    SZTextView              *inputTextView;
    UIView                  *textInputBG;
    UIView                  *photoInputView;
    UIView                  *voiceInputView;
    UIImageView             *photoInputIcon;
    UIImageView             *voiceInputIcon;
    
    UILabel                 *photoCntLabel;
    UIScrollView            *photoScrollView;
    
    FTWButton               *vpvplaybtn;
    FTWButton               *vpvdelbtn;
    FTWButton               *voiceBtn;
    FTWButton               *vpsendbtn;
    
    FaceBoard               *emojiInputView;
}

@end

@implementation WriteStatusViewController

-(id)init
{
    self = [super init];
    if (self != nil) {
        iSubmitTime = 0;
        iCommentState = CS_NULL;
        voiceTipsView = nil;
        iSTIndex = FCG_ONE_TEXT;
        emojiInputView = [[FaceBoard alloc]init];
    }
    
    return self;
}

-(void)initUI
{
    self.view.backgroundColor = VIEW_BG_COLOR;
    
    [self createTitle];
    self.mtitle.text = @"新动态";
    
    UIBarButtonItem *backItem = [self createBarBackButtonItemWithTitle:@"返回" target:self action:@selector(backButtonPressed)];
    self.navItem.leftBarButtonItem = backItem;
    
    UIBarButtonItem *nextItem = [self createBarButtonItemWithTitle:@"发布"
                                                            target:self
                                                            action:@selector(sendNewStatus:)];
    self.navItem.rightBarButtonItem = nextItem;
    
    inputTextView = [[SZTextView alloc]initWithFrame:CGRectMake(0, 44, 320, 120)];
    inputTextView.placeholder = @"说点什么吧";
    inputTextView.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18.0];
    inputTextView.userInteractionEnabled = YES;
    [self.view addSubview:inputTextView];
    
    UITapGestureRecognizer *singleTouch =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [inputTextView addGestureRecognizer:singleTouch];
    
    textInputBG = [[UIView alloc]initWithFrame:inputTextView.frame];
    textInputBG.backgroundColor = [UIColor clearColor];
    
    UIKeyboardCoView *keyboardBar = [[UIKeyboardCoView alloc]initWithFrame:CGRectMake(0, 410, 320, 44)];
    keyboardBar.delegate = self;
    keyboardBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:keyboardBar];
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    toolbar.barStyle = UIBarStyleBlack;
    
	voiceButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"voice_btn.png"] style:UIBarButtonItemStylePlain target:self action:@selector(showRecordView:)];
    photoButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"photo_btn.png"] style:UIBarButtonItemStylePlain target:self action:@selector(showPhotoSheet:)];
    faceButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fir_face.png"] style:UIBarButtonItemStylePlain target:self action:@selector(showFaceView:)];
    
    NSArray *buttons = [[NSArray alloc] initWithObjects:voiceButton,photoButton,faceButton,nil];
    
    [toolbar setItems:buttons animated:NO];
    
    [keyboardBar addSubview:toolbar];
    
    photoInputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 216)];
    photoInputView.backgroundColor = [UIColor colorWithRed:243.0/255.0 green:243.0/255.0 blue:243.0/255.0 alpha:1];
    
    photoInputIcon = [[UIImageView alloc]initWithFrame:CGRectMake(112, 27, 96, 96)];
    photoInputIcon.image = [UIImage imageNamed:@"bg_Photo_Input.png"];
    [photoInputView addSubview:photoInputIcon];
    
    FTWButton *cameraBtn = [[FTWButton alloc] init];
    cameraBtn.frame = CGRectMake(10, 150, 140, 44);
    [cameraBtn addBlueStyleForState:UIControlStateNormal];
    [cameraBtn setText:@"拍照" forControlState:UIControlStateNormal];
    [cameraBtn setFont:[UIFont systemFontOfSize:18]];
    [cameraBtn addTarget:self action:@selector(cameraBtnClip:) forControlEvents:UIControlEventTouchUpInside];
    [photoInputView addSubview:cameraBtn];
    
    FTWButton *albumBtn = [[FTWButton alloc] init];
    albumBtn.frame = CGRectMake(170, 150, 140, 44);
    [albumBtn addBlueStyleForState:UIControlStateNormal];
    [albumBtn setText:@"相册" forControlState:UIControlStateNormal];
    [albumBtn setFont:[UIFont systemFontOfSize:18]];
    [albumBtn addTarget:self action:@selector(albumBtnClip:) forControlEvents:UIControlEventTouchUpInside];
    [photoInputView addSubview:albumBtn];
    
    voiceInputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 216)];
    voiceInputView.backgroundColor = [UIColor colorWithRed:243.0/255.0 green:243.0/255.0 blue:243.0/255.0 alpha:1];
    
    voiceInputIcon = [[UIImageView alloc]initWithFrame:CGRectMake(112, 27, 96, 96)];
    voiceInputIcon.image = [UIImage imageNamed:@"bg_Voice_Input.png"];
    [voiceInputView addSubview:voiceInputIcon];
    
    voiceBtn = [[FTWButton alloc] init];
    voiceBtn.frame = CGRectMake(7, 150, 306, 44);
    [voiceBtn addBlueStyleForState:UIControlStateNormal];
    [voiceBtn setText:@"按住录音" forControlState:UIControlStateNormal];
    [voiceBtn setFont:[UIFont systemFontOfSize:18]];
    [voiceBtn addTarget:self action:@selector(voiceBtnClipUp:) forControlEvents:UIControlEventTouchUpInside];
    [voiceBtn addTarget:self action:@selector(voiceBtnClip:) forControlEvents:UIControlEventTouchDown];
    
    
    vpvplaybtn = [[FTWButton alloc] initWithFrame:CGRectMake(44, 150, 70, 44)];
    [vpvplaybtn addBlueStyleForState:UIControlStateNormal];
    [vpvplaybtn setText:@"播放" forControlState:UIControlStateNormal];
    [vpvplaybtn addTarget:self action:@selector(playRedio) forControlEvents:UIControlEventTouchUpInside];
    
    vpsendbtn = [[FTWButton alloc] initWithFrame:CGRectMake(124, 150, 70, 44)];
    [vpsendbtn addBlueStyleForState:UIControlStateNormal];
    [vpsendbtn setText:@"发送" forControlState:UIControlStateNormal];
    [vpsendbtn addTarget:self action:@selector(sendRedio) forControlEvents:UIControlEventTouchUpInside];
    
    vpvdelbtn = [[FTWButton alloc] initWithFrame:CGRectMake(204, 150, 70, 44)];
    [vpvdelbtn addDeleteStyleForState:UIControlStateNormal];
    [vpvdelbtn setText:@"删除" forControlState:UIControlStateNormal];
    [vpvdelbtn addTarget:self action:@selector(delRedio) forControlEvents:UIControlEventTouchUpInside];
    
    [voiceInputView addSubview:voiceBtn];
    
    photoCntLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 320, 30)];
    photoCntLabel.backgroundColor = [UIColor clearColor];
    photoCntLabel.textAlignment = NSTextAlignmentCenter;
    [photoInputView addSubview:photoCntLabel];
    
    photoScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 30, 320, 100)];
    photoScrollView.backgroundColor = [UIColor clearColor];
    photoScrollView.delegate = self;
    photoScrollView.showsHorizontalScrollIndicator = NO;
    photoScrollView.showsVerticalScrollIndicator = NO;
    [photoInputView addSubview:photoScrollView];
    
    [inputTextView becomeFirstResponder];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(inputEmoji:)
                                                 name:NOTIFICATION_FACE_INPUT
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(deleteEmoji:)
                                                 name:NOTIFICATION_FACE_DEL
                                               object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)backButtonPressed
{
    if (iSTIndex != FCG_ONE_SOUND) {
        [textInputBG removeFromSuperview];
        inputTextView.inputView = nil;
        [inputTextView reloadInputViews];
    }
    

    
    [[ViewManager sharedViewManager] backView:self];
}

-(void)showFaceView:(id)sender
{
    
        [inputTextView addSubview:textInputBG];
        inputTextView.inputView = emojiInputView;
        [inputTextView reloadInputViews];
    
}

- (void)sendNewStatus:(id)sender
{
    switch (iSTIndex) {
        case FCG_ONE_TEXT:
        {
            if ([self checkInput]) {
                
                if ([inputTextView isFirstResponder]) {
                    [inputTextView resignFirstResponder];
                }
                
                iCommentState = CS_SUBMIT;
                iSubmitTime = 0;
                
                [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在发布" withView:self.view];
                
                [[DataControl shareControl].fircirDS setFCSendIndex:iSTIndex];
                
                NSString *sendstr = inputTextView.text;
                
                if ([inputTextView.text isEqualToString:@""]) {
                    sendstr =
                     [NSString stringWithFormat:@"%@发布了图片",
                      [DataControl shareControl].personDS.uinfo.name];
                }
                
                [[DataControl shareControl].fircirDS SetFCSendContent:sendstr];
                
                [[netManager sharedNetManager].sendFCNewNews SendFCNewNews:FCG_ONE_TEXT
                                                               withContent:sendstr];
            }
        }
            break;
        case FCG_ONE_SOUND:
        {
            if ([inputTextView isFirstResponder]) {
                [inputTextView resignFirstResponder];
            }
            
            iCommentState = CS_SUBMIT;
            iSubmitTime = 0;
            
            [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在发布" withView:self.view];
            
            [[DataControl shareControl].fircirDS setFCSendIndex:iSTIndex];
            
            [[DataControl shareControl].fircirDS SetFCSendContent:
             [[recordManager shareControl].recordedFile path]];
            
            [[netManager sharedNetManager].sendFCNewNews SendFCNewNews:FCG_ONE_SOUND
                                                           withContent:
             [[recordManager shareControl].recordedFile path]];
        }
            break;
        default:
            break;
    }
    
}

-(bool)checkInput
{
    bool bcheck = true;
    
    if ([inputTextView.text isEqualToString:@""] &&
        [[DataControl shareControl].fircirDS getphotoArrCount] == 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"动态不能为空哦"
                                                       delegate:self
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil];
        [alert show];
        
        bcheck = false;
    }
    
    return bcheck;
}

- (void)showRecordView:(id)sender
{
    [inputTextView addSubview:textInputBG];
    inputTextView.inputView = voiceInputView;
    [inputTextView reloadInputViews];
}

- (void)showPhotoSheet:(id)sender
{
    [inputTextView addSubview:textInputBG];
    inputTextView.inputView = photoInputView;
    [inputTextView reloadInputViews];
}

- (void)handleTap:(UITapGestureRecognizer *)recognizer
{
    if (iSTIndex == FCG_ONE_SOUND) {
        return;
    }
    [textInputBG removeFromSuperview];
    inputTextView.inputView = nil;
    [inputTextView reloadInputViews];
}

- (void)inputEmoji:(NSNotification *)notification
{
    if ([ViewManager sharedViewManager].currentVC ==
        [ViewManager sharedViewManager].writeStatusvc) {
    NSNumber *index = (NSNumber *)[notification object];
    NSMutableString *faceString = [[NSMutableString alloc]initWithString:inputTextView.text];
    [faceString appendString:[emojiInputView._faceMap objectForKey:[NSString stringWithFormat:@"%03d",[index intValue]]]];
    [inputTextView setText:faceString];
    }
}

- (void)deleteEmoji:(NSNotification *)notification
{
    if ([ViewManager sharedViewManager].currentVC ==
        [ViewManager sharedViewManager].writeStatusvc) {
        NSString *inputString;
        inputString = inputTextView.text;
        
        NSString *string = nil;
        NSInteger stringLength = inputString.length;
        if (stringLength > 0) {
            if ([@"]" isEqualToString:[inputString substringFromIndex:stringLength-1]]) {
                if ([inputString rangeOfString:@"["].location == NSNotFound){
                    string = [inputString substringToIndex:stringLength - 1];
                } else {
                    string = [inputString substringToIndex:[inputString rangeOfString:@"[" options:NSBackwardsSearch].location];
                }
            } else {
                string = [inputString substringToIndex:stringLength - 1];
            }
        }
        [inputTextView setText:string];
    }
}


- (void)cameraBtnClip:(id)sender
{
    if ([[DataControl shareControl].fircirDS getphotoArrCount] < 9) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *picker=[[UIImagePickerController alloc]init];
            picker.sourceType=UIImagePickerControllerSourceTypeCamera;
            picker.delegate = self;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }else{
        UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:@"不要那么贪心哦" message:@"亲，你最多可以一次上传9张图片哦" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [errorAlert show];
    }
}

- (void)albumBtnClip:(id)sender
{
    if ([[DataControl shareControl].fircirDS getphotoArrCount] < 9) {
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.limitsMaximumNumberOfSelection = YES;
        imagePickerController.maximumNumberOfSelection = 9 - [[DataControl shareControl].fircirDS getphotoArrCount];
        
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
        [self presentViewController:navigationController animated:YES completion:NULL];
    }else{
        UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:@"不要那么贪心哦" message:@"亲，你最多可以一次上传9张图片哦" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [errorAlert show];
    }
}

- (void)voiceBtnClip:(id)sender
{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
    
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if(session == nil)
    {
        AS_LOG(@"Error creating session: %@", [sessionError description]);
    }
    else
        [session setActive:YES error:nil];
    
    if (nil == voiceTipsView) {
		voiceTipsView = [[FirCirVoiceTipsView alloc] initWithFrame:CGRectMake(70, -40, 184, 184)];
	}
	[voiceTipsView showPttStartImageBySuperView:voiceInputView];
    [voiceInputIcon setHidden:YES];
    [[recordManager shareControl] startRecord];
    iCommentState = CS_SOUND;
    voiceRecordTimer = [NSTimer scheduledTimerWithTimeInterval:0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
    iSubmitTime = 0;
}

- (void)reloadScrollView
{
    for(UIButton *subBtn in [photoScrollView subviews]) {
        [subBtn removeFromSuperview];
    }
    
    if ([[DataControl shareControl].fircirDS getphotoArrCount] > 0) {
        photoInputIcon.alpha = 0;
        photoCntLabel.text = [NSString stringWithFormat:@"已选择 %d张/9张 图片",
                              [[DataControl shareControl].fircirDS getphotoArrCount]];
        float imgViewWidth = 70;
        for (int photoCnt = 0; photoCnt < [[DataControl shareControl].fircirDS getphotoArrCount]; photoCnt++) {
            UIImage *img = [[DataControl shareControl].fircirDS getPhotoArrObjectIndex:photoCnt];
            
            float imgViewHeight = imgViewWidth*img.size.height/img.size.width;
            
            UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            imgBtn.tag = photoCnt;
            [imgBtn setBackgroundImage:img forState:UIControlStateNormal];
            imgBtn.frame = CGRectMake(photoCnt *imgViewWidth + 10*(photoCnt + 1) , 10, imgViewWidth, imgViewHeight);
            [imgBtn addTarget:self action:@selector(imageBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
            [photoScrollView addSubview:imgBtn];
            
            UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            delBtn.tag = photoCnt;
            [delBtn setBackgroundImage:[self closeButtonImage] forState:UIControlStateNormal];
            delBtn.frame = CGRectMake(imgBtn.frame.origin.x + imgViewWidth - 20, 0, 25, 25);
            [delBtn addTarget:self action:@selector(imageDelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
            [photoScrollView addSubview:delBtn];
        }
        photoScrollView.contentSize = CGSizeMake(80*[[DataControl shareControl].fircirDS getphotoArrCount] + 10, 100);
    }else{
        photoInputIcon.alpha = 1;
        photoCntLabel.text = nil;
    }
}

- (UIImage *)closeButtonImage{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(30, 30), NO, 0);
    
    //// General Declarations
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //// Color Declarations
    UIColor *topGradient = [UIColor colorWithRed:0.21 green:0.21 blue:0.21 alpha:0.9];
    UIColor *bottomGradient = [UIColor colorWithRed:0.03 green:0.03 blue:0.03 alpha:0.9];
    
    //// Gradient Declarations
    NSArray *gradientColors = @[(id)topGradient.CGColor,
    (id)bottomGradient.CGColor];
    CGFloat gradientLocations[] = {0, 1};
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations);
    
    //// Shadow Declarations
    CGColorRef shadow = [UIColor blackColor].CGColor;
    CGSize shadowOffset = CGSizeMake(0, 1);
    CGFloat shadowBlurRadius = 3;
    CGColorRef shadow2 = [UIColor blackColor].CGColor;
    CGSize shadow2Offset = CGSizeMake(0, 1);
    CGFloat shadow2BlurRadius = 0;
    
    
    //// Oval Drawing
    UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(4, 3, 24, 24)];
    CGContextSaveGState(context);
    [ovalPath addClip];
    CGContextDrawLinearGradient(context, gradient, CGPointMake(16, 3), CGPointMake(16, 27), 0);
    CGContextRestoreGState(context);
    
    CGContextSaveGState(context);
    CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow);
    [[UIColor whiteColor] setStroke];
    ovalPath.lineWidth = 2;
    [ovalPath stroke];
    CGContextRestoreGState(context);
    
    
    //// Bezier Drawing
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:CGPointMake(22.36, 11.46)];
    [bezierPath addLineToPoint:CGPointMake(18.83, 15)];
    [bezierPath addLineToPoint:CGPointMake(22.36, 18.54)];
    [bezierPath addLineToPoint:CGPointMake(19.54, 21.36)];
    [bezierPath addLineToPoint:CGPointMake(16, 17.83)];
    [bezierPath addLineToPoint:CGPointMake(12.46, 21.36)];
    [bezierPath addLineToPoint:CGPointMake(9.64, 18.54)];
    [bezierPath addLineToPoint:CGPointMake(13.17, 15)];
    [bezierPath addLineToPoint:CGPointMake(9.64, 11.46)];
    [bezierPath addLineToPoint:CGPointMake(12.46, 8.64)];
    [bezierPath addLineToPoint:CGPointMake(16, 12.17)];
    [bezierPath addLineToPoint:CGPointMake(19.54, 8.64)];
    [bezierPath addLineToPoint:CGPointMake(22.36, 11.46)];
    [bezierPath closePath];
    CGContextSaveGState(context);
    CGContextSetShadowWithColor(context, shadow2Offset, shadow2BlurRadius, shadow2);
    [[UIColor whiteColor] setFill];
    [bezierPath fill];
    CGContextRestoreGState(context);
    
    
    //// Cleanup
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

- (void)imageDelBtnClicked:(id)sender
{
    UIButton *delBtn = (UIButton*)sender;
    int index = delBtn.tag;
    [[DataControl shareControl].fircirDS RemovePhotoArrObjectByIndex:index];
    [self reloadScrollView];
}

- (void)imageBtnClicked:(id)sender
{
    UIButton *imgBtn = (UIButton*)sender;
    int index = imgBtn.tag;
    
    NSMutableArray *photos = [[NSMutableArray alloc]init];
    for (int imgCnt = 0; imgCnt < [[DataControl shareControl].fircirDS getphotoArrCount]; imgCnt++) {
        UIImage *img = [[DataControl shareControl].fircirDS getPhotoArrObjectIndex:imgCnt];
        MyPhoto *photo = [[MyPhoto alloc] initWithImage:img];
        [photos addObject:photo];
    }
    MyPhotoSource *source = [[MyPhotoSource alloc] initWithPhotos:photos];
    EGOPhotoViewController *photoController = [[EGOPhotoViewController alloc] initWithPhotoSource:source];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:photoController];
    
    navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    navController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:navController animated:YES completion:nil];
    [photoController moveToPhotoAtIndex:index animated:NO];
}

- (void)levelTimerCallback:(NSTimer *)timer {
	double power = [[recordManager shareControl] updateRecordPower];
    
    if (power == 0) {
        return;
    }
    
	int index = 0;
	if (power <= 0.1) {
		index = 1;
	}else if (power > 0.1 && power <= 0.2){
		index = 2;
	}else if (power > 0.2 && power <= 0.3){
		index = 3;
	}else if (power > 0.3 && power <= 0.4){
		index = 4;
	}else if (power > 0.4 && power <= 0.45) {
		index = 5;
	}else if (power > 0.45 && power <= 0.5){
		index = 6;
	}
	else if (power > 0.5){
		index = 7;
	}
	if (voiceTipsView) {
		[voiceTipsView updatePttSoundVolumImage:index];
	}
}

#pragma mark -private fun-
-(void)NewsSendSuccess
{
    if (iCommentState == CS_SUBMIT) {
        iCommentState = CS_NULL;
        iSubmitTime = 0;
        
        [[ViewManager sharedViewManager] ChangeHUDShowSuccess:@"发布成功！"];
        [self performSelector:@selector(backButtonPressed) withObject:nil afterDelay:1];
        
        [[DataControl shareControl].taskDS CompleteTaskByID:TI_F_NEWS
         withIsDirectShow:true];
    }
}

-(void)NewsSendFail
{
    if (iCommentState == CS_SUBMIT) {
        iCommentState = CS_NULL;
        iSubmitTime = 0;
        
        [[ViewManager sharedViewManager] ChangeHUDShowFail:@"发布太频繁，请稍后发布"];
        [self performSelector:@selector(showinputkey) withObject:nil afterDelay:1];
    }
    
}

-(void)viewWillShow
{
    [inputTextView becomeFirstResponder];
    [self cleanUI];
}

-(void)showinputkey
{
    if (![inputTextView isFirstResponder]) {
        [inputTextView becomeFirstResponder];
    }
}

-(void)UICustomTick
{
    switch (iCommentState) {
        case CS_SUBMIT:
        {
            if (iSubmitTime < 200) {
                iSubmitTime++;
            }
            else
            {
                iCommentState = CS_NULL;
                iSubmitTime = 0;
                
                [[ViewManager sharedViewManager] ChangeHUDShowFail:@"发布超时"];
                [self performSelector:@selector(showinputkey) withObject:nil afterDelay:1];
            }
        }
            break;
            case CS_SOUND:
        {
            iSubmitTime++;
        }
        default:
            break;
    }
}

-(void)voiceBtnClipUp:(id)sender
{
    iCommentState  = CS_NULL;
    if (iSubmitTime < 10) {
        [[recordManager shareControl] stopRecord];
        [voiceRecordTimer invalidate];
        [voiceTipsView showPttFailImage];
        [self performSelector:@selector(dismissVoiceTipsView) withObject:nil afterDelay:1.2];
    }
    else
    {
        [[recordManager shareControl] stopRecord];
        [voiceRecordTimer invalidate];
        iSubmitTime = 0;
        [self dismissVoiceTipsView];
        
        [vpvplaybtn setText:@"播放" forControlState:UIControlStateNormal];
        [voiceBtn removeFromSuperview];
        [voiceInputView addSubview:vpvplaybtn];
        [voiceInputView addSubview:vpvdelbtn];
        [voiceInputView addSubview:vpsendbtn];
        iSTIndex = FCG_ONE_SOUND;
        
        [inputTextView setPlaceholder:@"语音和文字不能同时输入哦"];
        [inputTextView setText:@""];
    }
    
    iSubmitTime = 0;
}

-(void)dismissVoiceTipsView
{
    [voiceTipsView dismissTips];
    [voiceInputIcon setHidden:NO];
}

-(void)playRedio
{
    if (player != nil && [player isPlaying]) {
        return;
    }
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
    
    if(session == nil)
    {
        AS_LOG(@"Error creating session: %@", [sessionError description]);
    }
    else
        [session setActive:YES error:nil];
    NSError *playerError;
    NSData *SpeexData = [NSData dataWithContentsOfFile:[[recordManager shareControl].recordedFile path]];
    NSData *NewPCMData = DecodeSpeexToWAVE(SpeexData);
    player = [[AVAudioPlayer alloc] initWithData:NewPCMData error:&playerError];
    AS_LOG(@"voice length is %f",player.duration);
    [player prepareToPlay];
    [player play];
}

-(void)sendRedio
{
    if (iSTIndex == FCG_ONE_SOUND) {
        
            if ([inputTextView isFirstResponder]) {
                [inputTextView resignFirstResponder];
            }
            
            iCommentState = CS_SUBMIT;
            iSubmitTime = 0;
            
            [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在发布" withView:self.view];
            
            [[DataControl shareControl].fircirDS setFCSendIndex:iSTIndex];
            
            [[DataControl shareControl].fircirDS SetFCSendContent:
             [[recordManager shareControl].recordedFile path]];
            
            [[netManager sharedNetManager].sendFCNewNews SendFCNewNews:FCG_ONE_SOUND
                                                           withContent:
             [[recordManager shareControl].recordedFile path]];
        
    }
}

-(void)delRedio
{
    [[FileManager shareControl] deleteFile:[[recordManager shareControl].recordedFile path]];    
    [vpvplaybtn removeFromSuperview];
    [vpvdelbtn removeFromSuperview];
    [vpsendbtn removeFromSuperview];
    [voiceInputView addSubview:voiceBtn];
    
    iSTIndex = FCG_ONE_TEXT;
    
    [inputTextView setPlaceholder:@"说点什么吧"];
}

-(void)cleanUI
{
    [inputTextView setText:@""];
    
    [vpvplaybtn removeFromSuperview];
    [vpvdelbtn removeFromSuperview];
    [vpsendbtn removeFromSuperview];
    [voiceInputView addSubview:voiceBtn];
    
    iSTIndex = FCG_ONE_TEXT;
    
    [[DataControl shareControl].fircirDS RemoveAllPhoto];
    
    [self reloadScrollView];
    
}

-(void)UpdateHUD
{
    iSubmitTime = 0;
    [[ViewManager sharedViewManager] ChangeHUDText:[[DataControl shareControl].fircirDS HubString]];
}

#pragma mark - QBImagePickerControllerDelegate

- (void)imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(id)info
{
    if ([imagePickerController isKindOfClass:[QBImagePickerController class]]) {
        if(imagePickerController.allowsMultipleSelection) {
            for (NSDictionary *photoDic in info) {
                UIImage *selectedImage = [photoDic valueForKey:UIImagePickerControllerOriginalImage];
                
                CGFloat width = selectedImage.size.width;
                CGFloat height = selectedImage.size.height;
                
                float verticalRadio = WINDOW_HIGTH*1.0/height;
                float horizontalRadio = WINDOW_WIDTH*1.0/width;
                
                float radio = 1;
                if(verticalRadio>1 && horizontalRadio>1)
                {
                    radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
                }
                else
                {
                    radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;
                }
                
                width = width*radio;
                height = height*radio;
                
                selectedImage = [selectedImage transformWidth:width height:height];
                
                
                [[DataControl shareControl].fircirDS AddPhotoArrObject:selectedImage];
            }
        }
    }else{
        UIImage *selectedImage = [info valueForKey:UIImagePickerControllerOriginalImage];
        
        CGFloat width = selectedImage.size.width;
        CGFloat height = selectedImage.size.height;
        
        float verticalRadio = WINDOW_HIGTH*1.0/height;
        float horizontalRadio = WINDOW_WIDTH*1.0/width;
        
        float radio = 1;
        if(verticalRadio>1 && horizontalRadio>1)
        {
            radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
        }
        else
        {
            radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;
        }
        
        width = width*radio;
        height = height*radio;
        
        selectedImage = [selectedImage transformWidth:width height:height];
        
        
        [[DataControl shareControl].fircirDS AddPhotoArrObject:selectedImage];
    }
    
    [self reloadScrollView];
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (NSString *)descriptionForSelectingAllAssets:(QBImagePickerController *)imagePickerController
{
    return @"选择全部照片";
}

- (NSString *)descriptionForDeselectingAllAssets:(QBImagePickerController *)imagePickerController
{
    return @"取消选择照片";
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfPhotos:(NSUInteger)numberOfPhotos
{
    return [NSString stringWithFormat:@"照片%d张,还可选择%d张", numberOfPhotos,
            9 - [[DataControl shareControl].fircirDS getphotoArrCount]];
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfVideos:(NSUInteger)numberOfVideos
{
    return [NSString stringWithFormat:@"视频%d个", numberOfVideos];
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfPhotos:(NSUInteger)numberOfPhotos numberOfVideos:(NSUInteger)numberOfVideos
{
    return [NSString stringWithFormat:@"照片%d张、视频%d个", numberOfPhotos, numberOfVideos];
}


#pragma mark - UI Keyboard Co View Delegate
- (void) keyboardCoViewWillAppear:(UIKeyboardCoView*)keyboardCoView{
}

- (void) keyboardCoViewDidAppear:(UIKeyboardCoView*)keyboardCoView{
}

- (void) keyboardCoViewWillDisappear:(UIKeyboardCoView*)keyboardCoView{
}


- (void) keyboardCoViewDidDisappear:(UIKeyboardCoView*)keyboardCoView{
}


@end
